package org.ko.core.websupport.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.ko.core.domain.auth.Permission;
import org.ko.core.domain.auth.Role;
import org.ko.core.domain.auth.User;
import org.ko.core.logic.auth.UserSvc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 
 * ShiroDbRealm
 * @author zengxm 药膏
 * @date 2014-9-17
 * @version 1.0.0
 */
@Service
@DependsOn(value={"userSvcImpl"})
public class ShiroDbRealm extends AuthorizingRealm{

	@Autowired
	private UserSvc userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//获取当前登录的用户名
		User loginU = (User)super.getAvailablePrincipal(principals);
		String account = loginU.getName();
		
		List<String> roles = new ArrayList<String>();  
		List<String> permissions = new ArrayList<String>();
		User user = userService.getByName(account);
		if(user != null){
			if (user.getRoles() != null && user.getRoles().size() > 0) {
				for (Role role : user.getRoles()) {
					roles.add(role.getName());
					if (role.getPermissions() != null && role.getPermissions().size() > 0) {
						for (Permission pmss : role.getPermissions()) {
							if(!StringUtils.isEmpty(pmss.getPermission())){
								String permission = pmss.getPermission();
								if(pmss.getParent() != null){
									permission = pmss.getParent().getPermission()+":"+permission;
								}else{
									permission = pmss.getPermission()+":*";
								}
								permissions.add(permission);
							}
						}
					}
				}
			}
		}else{
			throw new AuthorizationException();
		}
		//给当前用户设置角色
		info.addRoles(roles);
		//给当前用户设置权限
        info.addStringPermissions(permissions); 
        System.out.println("用户权限："+permissions.toString());
		return info;
	}

	/**
	 *  认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = userService.getByName(token.getUsername());
		if (user != null) {
			return new SimpleAuthenticationInfo(user, user
					.getPassword(), user.getName());
		} else {
			return null;
		}
	}
}

